package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"net"
	"os"
	"strings"
	"time"
)

type SocketMessage struct {
	Type int `json:"type"`
	UserId int `json:"user_id"`
	UserName string `json:"user_name"`
	Data map[string]interface{} `json:"data"`
}
var IsLogin = 0
var Messages SocketMessage
var SelfMessages  SocketMessage
func main() {

	//连接9009这个端口  连接服务端
	conn, err := net.Dial("tcp", "59.110.214.173:9009")
	//连接失败直接弹出
	if err != nil {
		fmt.Println("client dial err=", err)
		return 
	}

	go func(conn net.Conn) {
		buf := make([]byte, 1024)
		for {
			n, err := conn.Read(buf)
			if err != nil {
				fmt.Println("conn.Write err=", err)
			}
			_ = json.Unmarshal(buf[:n], &Messages)
			if IsLogin == 0 {
				if Messages.Type ==0 && Messages.UserId == 0 && Messages.Data["code"] != 200{
					fmt.Println(Messages.Data["message"])
					IsLogin = 0
					continue
				}

				if  Messages.Type ==0 && Messages.UserId != 0 {
					fmt.Println("登录成功")
					SelfMessages = Messages
					IsLogin = 1
					fmt.Println("规则:输入任意字符回车 即可发送")
					continue
				}
			}
			if IsLogin == 1  && Messages.UserId != SelfMessages.UserId && Messages.Type == 1{
				fmt.Println(Messages.UserName,"说",Messages.Data["message"])

			}
		}
	}(conn)

	//客户端可以发送单行数据，然后就退出
	reader := bufio.NewReader(os.Stdin) //os.Stdin 代表标准输入[终端]

	for {
		//从终端读取一行用户输入，并准备发送给服务器
		if IsLogin==0 {
			fmt.Println("请输入用户名")
			userName :=""
			fmt.Scanln(&userName)

			fmt.Println("请输入密码")
			userPass :=""
			fmt.Scanln(&userPass)

			sendData := SocketMessage{0,0,"", map[string]interface{}{"user_name":userName,"user_pass":userPass}}
			socketSend,_:=json.Marshal(sendData)

			//将JSON 发送给 服务器  然服务器转发给其他客户端
			_, err = conn.Write(socketSend)
			if err != nil {
				fmt.Println("conn.Write err=", err)
			}
			time.Sleep(time.Second*2)
			continue
		}
		line, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("readString err=", err)
		}
		//如果用户输入的是 exit就退出
		line = strings.Trim(line, " \r\n")
		if line == "exit" {
			fmt.Println("客户端退出..")
			break
		}
		SelfMessages.Data["message"] =  line + "\n"
		SelfMessages.Type = 1
		socketSendMess,_:=json.Marshal(SelfMessages)
		//再将line 发送给 服务器
		_, err = conn.Write(socketSendMess)
		if err != nil {
			fmt.Println("conn.Write err=", err)
		}

	}


}